package net.oschina.aibinxiao.scheduler;

import net.oschina.aibinxiao.job.HelloJob4;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: AiBinXiao
 * @Description: SimpleTrigger距离当前时间4秒后开首次执行任务，之后每隔2秒执行一次，一共执行三次
 * @Date: 2017/10/12 9:48
 */

public class HelloScheduler42 {
    public static void main(String[] args) throws SchedulerException {
        // 打印当前时间，格式为 yyyy-MM-dd HH:mm:ss
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = sdf.format(date);
        System.out.println("当前时间是：" + dateStr);

        // 创建一个JobDetail实例，将该实例与HelloJob Class绑定  传入自定义参数
        JobDetail jobDetail = JobBuilder.newJob(HelloJob4.class)
                .withIdentity("myjob42")
                .build();
        // 获取当前时间4秒后的时间
        date.setTime(date.getTime() + 4 * 1000);

        // 创建一个SimpleTrigger实例，距离当前时间4秒后开首次执行任务，之后每隔2秒执行一次，一共执行三次
        SimpleTrigger simpleTrigger = (SimpleTrigger) TriggerBuilder
                .newTrigger()
                .withIdentity("mytrigger42", "group42")
                .startAt(date)
                .withSchedule(
                        SimpleScheduleBuilder
                                .simpleSchedule()
                                .withIntervalInSeconds(2)
                                .withRepeatCount(3)
                )
                .build();

        // 创建Scheduler实例
        SchedulerFactory sfact = new StdSchedulerFactory();
        Scheduler scheduler = sfact.getScheduler();
        scheduler.start();
        scheduler.scheduleJob(jobDetail, simpleTrigger);
    }
}
